package com.zx.web.service.impl;

import com.zx.bean.Address;
import com.zx.bean.Cart;
import com.zx.bean.Order;
import com.zx.bean.OrderDetail;
import com.zx.utils.DataSourceUtils;
import com.zx.utils.RandomUtils;
import com.zx.web.dao.AddressDao;
import com.zx.web.dao.CartDao;
import com.zx.web.dao.OrderDao;
import com.zx.web.dao.OrderDetailDao;
import com.zx.web.dao.impl.AddressDaoImpl;
import com.zx.web.dao.impl.CartDaoImpl;
import com.zx.web.dao.impl.OrderDaoImpl;
import com.zx.web.dao.impl.OrderDetailDaoImpl;
import com.zx.web.service.OrderService;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * @author 章鑫
 * @version V1.0
 * @Project 2022-09-05
 * @Package com.zx.web.service.impl
 * @Description:
 * @Date 2022/9/15 19:02
 */
public class OrderServiceImpl implements OrderService {

    CartDao cartDao = new CartDaoImpl();
    OrderDao orderDao = new OrderDaoImpl();
    OrderDetailDao orderDetailDao = new OrderDetailDaoImpl();
    AddressDao addressDao = new AddressDaoImpl();

    @Override
    public Order addOrder(int aid, int userId) {

        Connection conn = DataSourceUtils.getConnection();
        try {
            conn.setAutoCommit(false);
            //查询购物车
            List<Cart> cartByUserId = cartDao.findCartByUserId(userId);
            //计算总金额
            int sum=0;
            for (Cart cart : cartByUserId) {
                sum+=cart.getMoney();
            }
            Order order = new Order();
            //随机生成订单编号
            String oId = RandomUtils.getTime();
            order.setId(oId);
            order.setUid(userId);
            order.setMoney(sum);
            order.setStatus("1");
            order.setTime(new Date());
            order.setAid(aid);
            orderDao.addOrder(order);
            for (Cart cart : cartByUserId) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOid(oId);
                orderDetail.setPid(cart.getPid());
                orderDetail.setNum(cart.getNum());
                orderDetail.setMoney(cart.getMoney());
                orderDetailDao.addOrderDetail(orderDetail);
            }
            cartDao.clearCartById(userId);
            conn.commit();
            return order;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return  null;
    }

    @Override
    public void updateStatus(String id) {
        orderDetailDao.updateStatus(id);
    }

    @Override
    public List<Order> findOrderById(int id) {

        List<Order> orderList = orderDao.findOrderById(id);

        for (Order order : orderList) {
            Address address = addressDao.findAddress(order.getAid());
            order.setAddress(address.getDetail());
        }

        return orderList;
    }
}
